import { Notification } from "element-ui";
import _ from "lodash";
import contentTypes from "./content-types";
import store from "../../store";
import router from "../../router";

function initConfigAuth(config) {
  if (sessionStorage.getItem("AccessToken")) {
    const token = sessionStorage.getItem("AccessToken");
    config.headers.AccessToken = token;
  }
  return config;
}

function initConfigHeader(config) {
  config.headers["Content-Type"] = contentTypes[config.iContentType].header;

  return config;
}

function initConfigData(config) {
  let data = config.data || {};

  if (config.transRequestData instanceof Function)
    data = config.transRequestData(data);

  if (config.params) {
    // get请求，合并参数
    data = { ...data, ...config.params };
  } else {
    data = contentTypes[config.iContentType].trans(data);
  }

  config.data = data;
  return config;
}

function handlerResponse(response, alias) {
  const { resultData, resultMsg, resultCode, successCode, unLoginCode } = alias;
  let data = response.data; // status == 200时的处理
  if (data[resultCode] !== successCode) {
    // 接口错误

    if (data[resultCode] == unLoginCode) {
      // 用户登录失败，或未登录
      store.commit("clearAuth");
      router.push({ name: "Login" });
      NotificationInstance("warning", {
        message: "用户未登录或登录失效",
      });
    } else if (!response.config.errorHandle) {
      // 可在请求时在header里面设置参数表示自己处理异常
      NotificationInstance("warning", {
        message: data[resultMsg] || "操作失败，请稍后重试",
      });
    }

    return Promise.reject(data);
  } else {
    if(!resultData) {
      return data
    }
    const dataFields = resultData.split(",")
    if(dataFields.length === 1) {
      return data[dataFields[0]]
    }
    const result = {}
    dataFields.forEach(field => {
      result[field] = data[field]
    })
    return result
  }
}

// 请求失败，如网络、路径问题
function handlerError(error) {
  // 请求错误，统一处理即可，不需要业务处理
  console.dir(error);
  console.error(error)

  if (
      error.code === "ECONNABORTED" &&
      error.message.indexOf("timeout") !== -1
  ) {
    // 请求超时
    NotificationInstance("warning", {
      title: "提示",
      message: "请求超时",
    });
  } else {
    NotificationInstance("warning", {
      title: "提示",
      message:
          "服务器开小差了，请稍后重试，状态码：" +
          (error.response && error.response.status),
    });
  }
  return Promise.reject(error); // 是否需要返回
}

function NotificationOnce() {
  const notifications = [];

  return (type, options) => {
    if (
        notifications.length &&
        notifications.find((no) => no.message === options.message)
    ) {
      return;
    }

    const instance = Notification[type](options);
    notifications.push(instance);
    const duration = options.duration || 2000;
    setTimeout(() => {
      _.remove(notifications, (item) => item === instance);
    }, duration);
  };
}

const NotificationInstance = NotificationOnce();

export {
  initConfigAuth,
  initConfigHeader,
  initConfigData,
  handlerResponse,
  handlerError,
};
